var router = require('express').Router();
var util = require('util');
var uuid = require('node-uuid');
var cookie = require('cookie');
var LRU = require('lru-cache');
var EventProxy = require('eventproxy');
var async = require('async');

var Consts = require('../consts');
var resultJson = require('../result-json');
var Utils = require('../utils');
var logger = require('../models/logger');
var User = require('../models/User');
var Group = require('../models/Group');
var GroupMessage = require('../models/GroupMessage');
var CryptoJS = require("../CryptoJS");
var SMSSend = require('../sms-utils');
var Message = require('../models/Message');

router.post('/', function(req, res) {
	res.send('respond with a resource');
});

//创建群
router.post('/newGroupChat', function(req, res) {
	var groupChatName = req.body.from;
	groupChatName = "未命名";
	var userid = req.body.userid;
	var checkArrs = req.body.friendId;
	console.log("checkArrs="+checkArrs);

	if (!groupChatName)
		return res.send(resultJson(3));

		var  newGroup = new Group();
		newGroup.name=groupChatName;
		newGroup.createtime=new Date();
		newGroup.userid=userid;
		newGroup.groupuserid=checkArrs;
		newGroup.save(
          function(err) {
          	if (err)
				return res.send(resultJson(2));
		    var groupid = ""+newGroup._id;
		    var count = 0;
            for(var i=0;i<checkArrs.length;i++){
			User.update({_id:checkArrs[i]},{$addToSet:{group:groupid}},function(err){
				if (err){
					return res.send(resultJson(2));
				}
				++count;
				if(count==checkArrs.length){
			  		 return res.send(resultJson(0,newGroup));
				}
				
			});
		 } 
		  
		});

/*	Group.count({
		name: groupChatName
	}, function(err, cnt) {
		if (err)
			return res.send(resultJson(2));
		if (cnt)
			return res.send(resultJson(301));
         //保存好友
	});*/
});

//将用户添加到群中
router.post('/addUserToGroup', function(req, res) {
var userid = req.body.userid;//一维数组对象
var _id = req.body._id;//群的id
	console.log(userid);
	console.log(_id);
	if (!userid||!_id)
		return res.send(resultJson(3));

	Group.update({
		_id: _id,
	}, {
		$addToSet: {
		groupuserid:{$each:userid}
		},
	}, function(err) {
		console.log(err);
		if (err)
			return res.send(resultJson(2));
		console.log("添加好友成功");
		User.update({
			_id: {$in:userid},
		}, {
			$addToSet: {
			group:_id
			},
		}, function(err) {
			if (err)
				return res.send(resultJson(2));
			res.send(resultJson(0));
		});		
	});
});

//删除并退出群
router.post('/removeGroup', function(req, res) {
	var userid = req.body.userid;//一维数组对象
	var _id = req.body.groupKeyId;//群的id
	var id = req.body.id;

	if (!userid||!_id)
	return res.send(resultJson(3));
    //从群中移除用户
    Group.update({
		_id: _id,
	}, {
		$pullAll: {
		groupuserid:userid
		},
	}, function(err) {
		
		if (err)
			return res.send(resultJson(2));
		console.log("从群中移除用户");
		//从用户中移除群
		User.update({
			_id: {$in:userid},
		}, {
			$pull: {
			group:_id
			},
		}, function(err) {
			if (err)
				return res.send(resultJson(2));
			console.log("从用户中移除群");
			//如果是群里最后一个人退出，则删除群并清空该群里的所有聊天信息
			//TODO:获取对象失败
			Group.findOne({_id:_id,},function(err,group){
				if (err)
			      return res.send(resultJson(2));
			  			console.log("groupuserid="+group.groupuserid);
			var totalPerson = group.groupuserid.length;

			console.log("目前群里的总人数："+totalPerson);
					   if(totalPerson==0){
						Group.remove({
							_id:_id
						},function(err){
		                   if(err){
								return res.send(resultJson(2));
		                   }
		                  console.log("移除群");
				                GroupMessage.remove({
									groupid:_id
								},function(err){
				                   if(err){
										return res.send(resultJson(2));
				                   }
				                   console.log("清空聊天信息");
				                   res.send(resultJson(0));
								});
						});
					}//end if
					else{
						res.send(resultJson(0));	
					}
			});



			
		});		
	});
});

//从群删除好友
router.post('/removeFriendsFromGroup', function(req, res) {
	var userid = req.body.userid;//一维数组对象
	var _id = req.body.groupKeyId;//群的id
	

	if (!userid||!_id)
	return res.send(resultJson(3));
    //从群中移除用户
    Group.update({
		_id: _id,
	}, {
		$pullAll: {
		groupuserid:userid
		},
	}, function(err) {
		
		if (err)
			return res.send(resultJson(2));
		console.log("从群中移除用户");
		//从用户中移除群
		User.update({
			_id: {$in:userid},
		}, {
			$pull: {
			group:_id
			},
		}, function(err) {
			if (err)
				return res.send(resultJson(2));
				res.send(resultJson(0));
	
		});		
	});
});

//展示群详细信息
router.post('/detail', function(req, res) {
	var _id = req.body._id;//群主键
	if (!_id)
		return res.send(resultJson(3));

	Group.findOne({
		_id: _id
	}).exec(function(err, group) {
		if (err) {
			logger.error(err);
			return res.send(resultJson(2));
		}
		group = JSON.parse(JSON.stringify(group));
		return res.send(resultJson(0, group));
	});
});

//群列表
router.post('/groupList', function(req, res) {
	var _id = req.body._id;
	 if (!_id)
		return res.send(resultJson(3));
	User.findOne({
		_id: _id,
	}).exec(function(err, user) {
		if (err) {
			logger.error(err);
			return res.send(resultJson(2));
		}
		  user = JSON.parse(JSON.stringify(user));
		  var groupArrs = new Array();
          var count = 0;
		 for(var i=0&&user.group;i<user.group.length;i++){
		 	           var groupId = user.group[i];
			          	Group.findOne({
			          	    _id:groupId
			          	    }, function(err, groups) {
			          			if (!err) {
                                 ++count;
								groupArrs.push(groups);
								  if(count==user.group.length){
								  return res.send(resultJson(0,groupArrs));
								}
							}else{
							    logger.error(err);
								return res.send(resultJson(2));	
							}
						});//end find
		   }//end for
		   if(user.group.length==0){
                return res.send(resultJson(0,groupArrs));
           }
	});
});

//更新群名
router.post('/updateGroupName', function(req, res) {
	var groupKeyId = req.body.groupKeyId;
	var name = req.body.groupName;
	if (!groupKeyId || !name)
		return res.send(resultJson(3));

	Group.update({
		_id: groupKeyId,
		
	}, {
		$set: {
			name: name,
		},
	}, function(err) {
		if (err)
			return res.send(resultJson(2));
		return res.send(resultJson(0));
	});
});
/**获取指定群中的用户集合信息：*/
router.post('/getUserListByGroupId', function(req, res) {
	var groupKeyId = req.body.groupKeyId;
	
	if (!groupKeyId)
		return res.send(resultJson(3));

	Group.findOne({
		_id: groupKeyId,
		
	}, function(err,group) {
		if (err)
			return res.send(resultJson(2));
		getGroupFriendList(res,group.groupuserid)
	});
});
function getGroupFriendList(res,friendList){
	var friendArrs = new Array();
	var count=0;
    for(var i=0;i<friendList.length;i++){
    		User.findOne({
					_id: friendList[i],
			},{
				_id:1,
				name:1,
				photo:1,
				phone:1,
			},function(err,user){
		        if(err){
		          return res.send(resultJson(2));
		        }
		       ++count;
		      friendArrs.push(user);
		      
		      if(count==friendList.length){
		      	console.log(friendArrs);
 				return res.send(resultJson(0,friendArrs));
		      }
			});
    }

}

module.exports = router;